<?php

namespace App\Http\Controllers\Api;

use App\Http\Servers\Admin\BaseServer;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class ApiController extends Controller
{
    private $key;
    private $config;

    //生成验证用key
    public function __construct(BaseServer $baseServer)
    {
        $this->key = md5(date('Y-m-d') . 'miya');
        $this->config = $baseServer->getConfig();
    }

    //验证key是否正确
    public function verify_key($key)
    {
        return $key === $this->key;
    }

    //软件登录用api
    public function login(Request $request)
    {
        $name = $request->account;
        $password = $request->pwd;
        if (\Auth::guard('admin')->attempt(['name' => $name, 'password' => $password, 'status' => 1])) {
            return [
                'status' => true,
                'code' => 10000,
                'data' => [
                    'uid' => \Auth::guard('admin')->user()->id,
                    'uname' => \Auth::guard('admin')->user()->name,
                ]
            ];
        } else {
            return [
                'status' => false,
                'code' => 10002
            ];
        }
    }

    //软件登录网站管理后台api
    public function sw_login(Request $request)
    {
        $name = $request->uname;
        $password = $request->upwd;
        if (\Auth::guard('admin')->attempt(['name' => $name, 'password' => $password, 'status' => 1])) {
            $message['message'] = message(true, '登录成功!', '后台登录成功!');
            if ($request->has('chunk')) {
                return redirect()->route('admin.info.info_add', $request->chunk)->with($message);
            }
            return redirect()->route('admin.index.index')->with($message);
        } else {
            return redirect()->route('admin.auth.getlogin');
        }
    }

    //软件登录网站管理后台跳转到在线留言列表api
    public function message(Request $request)
    {
        $name = $request->uname;
        $password = $request->upwd;
        if (\Auth::guard('admin')->attempt(['name' => $name, 'password' => $password, 'status' => 1])) {
            return redirect()->route('admin.message.message');
        } else {
            return redirect()->route('admin.auth.getlogin');
        }
    }


    //获取网站的大体信息
    public function getinfo(Request $request, BaseServer $baseServer)
    {
        header("Content-type: text/html; charset=utf-8");
        if ($this->verify_key($request->key)) {
            $data['网站名称'] = $this->config['web_name'];
            $data['网站域名'] = $this->config['web_url'];
            $data['百度统计页面'] = $this->config['web_count_url'];
            $data['网站关键词'] = array_values($baseServer->getKeywordsWithAreaAndLong()['group']);
            $data['主营地区'] = implode(',', $baseServer->getKeywordsWithAreaAndLong()['area']);
            $data['操作系统'] = PHP_OS;
            $data['运行环境'] = $_SERVER["SERVER_SOFTWARE"];
            $data['PHP运行方式'] = php_sapi_name();
            $data['上传附件限制'] = ini_get('upload_max_filesize');
            $data['执行时间限制'] = ini_get('max_execution_time') . '秒';
            $data['服务器时间'] = date("Y-m-d H:i:s");
            $data['北京时间'] = gmdate("Y-m-d H:i:s", time() + 8 * 3600);
            $data['服务器域名/IP'] = $_SERVER['SERVER_NAME'] . ' [ ' . gethostbyname($_SERVER['SERVER_NAME']) . ' ]';
            $data['剩余空间'] = round((disk_free_space(".") / (1024 * 1024)), 2) . 'M';
            $data['总空间'] = round((disk_total_space(".") / (1024 * 1024)), 2) . 'M';

            $infostr = json_encode($data, JSON_UNESCAPED_UNICODE);
            echo '{"status":true,"code":10000,"data":' . $infostr . '}';
        } else {
            return [
                'status' => false,
                'code' => '10001'
            ];
        }
    }

    public function modelinfo(Request $request)
    {
        if ($this->verify_key($request->key)) {
            $chunks = \App\Chunk::where('chunks.status', 1)
                ->leftjoin('info_sort_lines', 'info_sort_lines.chunk', '=', 'chunks.id')
                ->leftjoin('infos', 'infos.id', '=', 'info_sort_lines.info')
                ->select('chunks.name', \DB::raw('count(infos.id) as num'), \DB::raw('max(infos.created_at) as time'))
                ->orderBy('time', 'DESC')
                ->groupBy('chunks.name')
                ->take(2)
                ->get()
                ->toArray();
            foreach ($chunks as $k => $chunk) {
                $chunks[$k]['frequency'] = '每周';
                $chunks[$k]['score'] = 10;
            }
            $infostr = json_encode($chunks, JSON_UNESCAPED_UNICODE);
            echo '{"status":true,"code":10000,"data":' . $infostr . '}';
        } else {
            return [
                'status' => false,
                'code' => 10001
            ];
        }
    }

    //得到友情链接数量
    public function getlinknum(Request $request)
    {
        if ($this->verify_key($request->key)) {
            $num = \App\FriendlyLink::count();
            echo '{"status":true,"code":10000,"data":{"num":"' . $num . '"}}';
        } else {
            return [
                'status' => false,
                'code' => 10001,
            ];
        }
    }

    //得到在线留言信息
    public function getmsginfo(Request $request)
    {
        if ($this->verify_key($request->key)) {
            $messages = \App\Message::where('status', 1)
                ->select('id as msg_id', 'message_field_1 as msg_from', 'created_at as msg_time', 'message_field_2 as msg_phone', 'message_field_3 as msg_email', 'message_field_4 as msg_content', 'status as msg_status')
                ->get()
                ->toArray();
            $infostr = json_encode($messages, JSON_UNESCAPED_UNICODE);
            echo '{"status":true,"code":10000,"data":' . $infostr . '}';
        } else {
            return [
                'status' => false,
                'code' => 10001,
            ];
        }
    }

    //得到需要同步的信息
    public function getwebinfo(Request $request)
    {
        if ($this->verify_key($request->key)) {
            $data['name'] = \App\Set::where('name', 'web_name')->value('value');

            $data['about'] = \App\PageInfo::where('id', config('app.aboutid'))->value('describe');

            $data['contact'] = \App\PageInfo::where('id', config('app.connectid'))->value('describe');

            $data['email'] = \App\Set::where('name', 'web_email')->value('value');

            $data['password'] = \App\Admin::where('id', 1)->value('password');

            $data['phone'] = \App\Set::where('name', 'web_phone')->value('value');

            return $data;
        }
    }

    //收集软件上传的seo查询信息
    public function syncseo(Request $request)
    {
        if ($this->verify_key($request->key)) {
            $seo = json_decode($request->seo, true);
            $create['ip'] = $seo['ip'];
            $create['seo_content'] = json_encode($seo['seo']);

            $result = \App\Seo::create($create);
            if ($result) {
                echo '{"status":true,"code":10000}';
            } else {
                return [
                    'status' => 'false',
                    'code' => 10001
                ];
            }
        }
    }

    //显示软件的同步信息
    public function showseo(Request $request)
    {
        $name = $request->uname;
        $password = $request->upwd;
        if (\Auth::guard('admin')->attempt(['name' => $name, 'password' => $password, 'status' => 1])) {
            return redirect()->route('admin.seo.sync_data');
        } else {
            return redirect()->route('admin.auth.getlogin');
        }
    }

    //得到最近7条seo同步记录
    public function getseo(Request $request)
    {
        header("Content-type: text/html; charset=utf-8");
        if ($this->verify_key($request->key)) {
            $seo = \App\Seo::take(7)
                ->orderBy('id', 'DESC')
                ->get()
                ->toArray();
            if (count($seo) > 0) {
                foreach ($seo as $k => $v) {
                    //得到排名数量
                    $seo[$k]['seo_num'] = count(json_encode($seo[$k]['seo_content'], true));
                    //得到排名情况
                    $seo[$k]['seo_content'] = json_decode($seo[$k]['seo_content'], true);
                    //得到时间
                    $seo[$k]['seo_time'] = $v['created_at'];
                    //处理ip
                    $ipinfo = json_decode(file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=' . $v['ip']), true);
                    $seo[$k]['seo_area'] = $ipinfo['country'] . '-' . $ipinfo['province'] . '-' . $ipinfo['city'];
                }
                $infostr = json_encode($seo
                    , JSON_UNESCAPED_UNICODE);
                echo '{"status":true,"code":10000,"data":' . $infostr . '}';
            } else {
                return [
                    'status' => false,
                    'code' => 10009
                ];
            }
        }
    }
}
